package com.wfx.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.wfx.entity.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * <p>title: com.wfx.controller</p>
 * author zhuximing
 * description:
 */
@RestController
@CrossOrigin
@Api(description = "文件上传")
public class UploadController {


    @Value("${qiniu.ak}")
    private String ak;
    @Value("${qiniu.sk}")
    private String sk;
    @Value("${qiniu.bucket}")
    private String bucketName;
    @Value("${qiniu.url}")
    private String url;


    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result upload(MultipartFile headerImage)throws Exception{
        //获取文件的字节数组
        byte[] bytes = headerImage.getBytes();
        //构造一个带指定 Region 对象的配置类(必须正确指定区 )
        Configuration cfg = new Configuration(Region.huanan());

        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey =ak;
        String secretKey = sk;
        String bucket = bucketName;

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString()+headerImage.getOriginalFilename();

        try {
            Auth auth = Auth.create(accessKey, secretKey);
            //校验ak和sk，如果合法，那么办法token
            String upToken = auth.uploadToken(bucket);

            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            ObjectMapper mapper = new ObjectMapper();
            DefaultPutRet putRet = mapper.readValue(response.bodyString(),DefaultPutRet.class);

            System.out.println(putRet.key);

            System.out.println(putRet.hash);

            //文件的完整访问路径
            String path = url+putRet.key;
            System.out.println(path);
            return  new Result(true,"上传成功",path);

        } catch (Exception ex) {
            //ignore
            ex.printStackTrace();
        }
        return  new Result(false,"上传失败");
    }
}